package com.linhh.mall.center.web.controller;

import com.csvreader.CsvWriter;
import com.github.pagehelper.PageInfo;
import com.linhh.mall.center.api.OrderInfoService;
import com.linhh.mall.center.common.dto.OrderCount;
import com.linhh.mall.center.common.dto.OrderTimeDataDto;
import com.linhh.mall.center.common.exception.DefinitionException;
import com.linhh.mall.center.common.pojo.OrderDelivery;
import com.linhh.mall.center.common.pojo.OrderItem;
import com.linhh.mall.center.common.pojo.SubOrderInfo;
import com.linhh.mall.center.common.util.HttpResult;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author linhh
 * @Date 2023 02 21 02 49
 **/
@RestController
@RequestMapping("/api")
public class OrderController {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     *
     */
    @Reference
    private OrderInfoService orderInfoService;
    @GetMapping(value = "/storeOrder")
    public HttpResult getStoreOrder(Long shopId, Integer orderStatus, @RequestParam(value = "page",defaultValue = "1")int pageNo, @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        PageInfo<SubOrderInfo> subOrderInfoPageInfo = orderInfoService.queryAll(shopId,orderStatus,pageNo+1,pageSize);
        return HttpResult.success(subOrderInfoPageInfo);
    }

    /**
     *
     * @param suborderId
     * @return
     */
    @GetMapping(value = "/getDetailInfo/{id}")
    public HttpResult getDetailInfo(@PathVariable("id") Long suborderId){
        List<OrderItem> orderItemList = orderInfoService.getDetailInfo(suborderId);
        if(orderItemList!=null&&orderItemList.size()<=0){
            return HttpResult.defineError(new DefinitionException("获取商品列表为空"));
        }
        return HttpResult.success(orderItemList);
    }

    /**
     *
     * @param subOrderId
     * @return
     */
    @GetMapping("/getDeliveryInfo/{id}")
    public HttpResult getDeliverInfo(@PathVariable("id")Long subOrderId){
        OrderDelivery orderDelivery = orderInfoService.getDeliveryInfo(subOrderId);
        if(orderDelivery==null){
            return HttpResult.defineError(new DefinitionException("暂无此订单配送消息"));
        }
        return HttpResult.success(orderDelivery);
    }

    /**
     *
     * @param shopId
     * @return
     */
    @GetMapping(value = "/StoreOrder/orderCount")
    public ResponseEntity orderCount(@RequestParam(value = "shopId",defaultValue = "0")Long shopId){
        OrderCount orderCount = orderInfoService.getOrderCount(shopId);
        return new ResponseEntity(orderCount, HttpStatus.OK);
    }

    /**
     *
     * @param shopId
     * @return
     */
    @GetMapping(value = "/data/count")
    public ResponseEntity selectCount(@RequestParam(value = "shopId",defaultValue = "0")Long shopId){
        OrderTimeDataDto orderTimeDataDto = orderInfoService.orderTimeDate(shopId);
        return new ResponseEntity(orderTimeDataDto,HttpStatus.OK);
    }

    /**
     *
     * @param shopId
     * @return
     */
    @GetMapping(value = "/data/chart")
    public ResponseEntity getChart(@RequestParam(value = "shopId",defaultValue = "0")Long shopId){
        Map<String,Object> map = orderInfoService.chartCount(shopId);
        return new ResponseEntity(map,HttpStatus.OK);
    }

    /**
     * 子订单列表文件下载
     * @param response
     * @param shopId
     * @param orderStatus
     * @param page
     * @param size
     */
    @GetMapping("/storeOrder/download")
    public void downloadOrder(HttpServletResponse response,Long shopId,Integer orderStatus,int page,int size){
        CsvWriter csvWriter = null;
        OutputStream outputStream = null;

        try{
            outputStream = response.getOutputStream();
            // 创建CsvWriter对象
            csvWriter = new CsvWriter(outputStream,',', Charset.forName("UTF-8"));
            // 构建头部信息
            String[] headers = {"ID","订单ID","会员ID","店铺名称","付款时间","地址","创建时间","更新时间"};
            csvWriter.writeRecord(headers);
            // 获取子订单列表
            List<SubOrderInfo> subOrderInfos = orderInfoService.selectAll();
            int result = 0;
            for (SubOrderInfo subOrderInfo:subOrderInfos){
                List<String> contentList = new ArrayList<>();
                contentList.add(String.valueOf(subOrderInfo.getId()));
                contentList.add(String.valueOf(subOrderInfo.getOrderId()));
                contentList.add(String.valueOf(subOrderInfo.getMemberId()));
                contentList.add(String.valueOf(subOrderInfo.getShopName()));
                contentList.add(sdf.format(subOrderInfo.getPayTime()));
                contentList.add(subOrderInfo.getAddress());
                contentList.add(sdf.format(subOrderInfo.getCreateTime()));
                contentList.add(sdf.format(subOrderInfo.getUpdateTime()));
                String[] array = contentList.toArray(new String[contentList.size()]);
                // 写入每行记录
                csvWriter.writeRecord(array);
                result++;
            }
            // 配置文件下载
            response.setHeader("content-type","application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载能正常显示正常中文
            response.setHeader("Content-Disposition","attachment;filename=");
            System.out.println("download the file successfully");
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            // 关闭csvWriter
            if (csvWriter != null){
                csvWriter.close();
            }
        }
    }

}
